

import 'package:isar/isar.dart';

import 'db_manager.dart';


//flutter pub run build_runner build 生成
part 'isar_key_value_model.g.dart';

///此类利用数据库的安全性，存储键值对
@Collection()
class IsarKeyValueModel {
  Id? ids;
  String? key;
  String? value;

  IsarKeyValueModel();

  IsarKeyValueModel.create(this.key, this.value);

  ///更新，外部不能调用
  static void _update(IsarKeyValueModel model) {
    DatabaseManager.getInstance().saveData(() async {
      await DatabaseManager.getInstance()
          .isar
          ?.isarKeyValueModels
          .filter()
          .keyEqualTo(model.key)
          .deleteAll();
    }).then((value) => _put(model));
  }

  ///增加，外部不能调用
  static void _put(IsarKeyValueModel model) async {
    DatabaseManager.getInstance().saveData(() async {
      await DatabaseManager.getInstance().isar?.isarKeyValueModels.put(model);
    });
  }

  ///保存当前键值对
  static void save(IsarKeyValueModel model) async {
    if (isKeyExist(model.key)) {
      _update(model);
    } else {
      _put(model);
    }
  }

  ///某个键值对是否存在
  static bool isKeyExist(String? key) {
    List<IsarKeyValueModel>? models = DatabaseManager.getInstance()
        .isar
        ?.isarKeyValueModels
        .filter()
        .keyEqualTo(key)
        .findAllSync();
    if (models == null || models.isEmpty) return false;
    return true;
  }

  ///找个当前值
  static IsarKeyValueModel? findModel(String? key) {
    if (isKeyExist(key)) {
      List<IsarKeyValueModel>? models = DatabaseManager.getInstance()
          .isar
          ?.isarKeyValueModels
          .filter()
          .keyEqualTo(key)
          .findAllSync();
      return models?.first;
    }
    return null;
  }

  ///统一管理已存的key值，增加属性在下面增加一个key
  static const String account = "account";
  static const String password = "password";
  static const String language = "language";
  static const String user = "user";
}

